<template>
  <a-upload :disabled="disabled" list-type="picture-card" :limit="limit" :on-before-remove="remove" :on-before-upload="beforeUplaod" action="/" v-model:file-list="fileList" image-preview />
</template>

<script lang="ts">
  import { defineComponent, ref, watch } from 'vue'
  import { uplaodImg } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import { dataTool } from 'echarts/core'
  const fileType: Array<string> = ['JPG', 'PNG', 'BMP', 'GIF', 'JPEG']
  export default defineComponent({
    name: 'uploadImg',
    props: ['limit', 'modelValue', 'disabled'],
    setup(props, { emit }) {
      const fileList: any = ref([])
      const beforeUplaod: any = async (file: any) => {
        console.log(file)
        let type = file.type.split('/')[1]
        if (!fileType.includes(type.toUpperCase())) {
          Message.error('请上传JPG/PNG/BMP/GIF/JPEG格式的图片')
          return false
        }

        if (file.size / 1024 / 1024 > 5) {
          Message.error('图片最大为4M')
          return false
        }
        // return
        let formData = new FormData()
        formData.append('file', file)
        const res: any = await uplaodImg(formData)
        if (res.code == 'SUCCESS') {
          fileList.value.push({ url: res.data.publicUrl })
        }
        if (props.limit == 1 && typeof props.modelValue == 'string') {
          emit('update:modelValue', res.data.publicUrl)
        } else {
          emit('update:modelValue', fileList.value)
        }

        emit('uploadSuccess', file)
      }

      watch(
        () => props.modelValue,
        (val) => {
          fileList.value = []
          if (val && typeof props.modelValue == 'string') {
            fileList.value.push({ url: val })
          } else {
            if (val && val.length > 0 && props.limit != 1) {
              fileList.value = val.filter((e: any) => e.url)
            } else if (val && val.length > 0 && props.limit == 1) {
              if (val[0].url) fileList.value.push(val[0])
            }
          }
        },
        { immediate: true, deep: true }
      )

      const remove = (val: any) => {
        let index = fileList.value.findIndex((e: any) => e.url == val.url)
        fileList.value.splice(index, 1)
        if (props.limit == 1 && typeof props.modelValue == 'string') {
          emit('update:modelValue', '')
        } else {
          emit('update:modelValue', fileList.value)
        }
      }

      return {
        fileList,
        beforeUplaod,
        remove,
      }
    },
  })
</script>

<style lang="less" scoped></style>
